{% extends "base/_base.html" %}
{% load staticfiles %}


{% block  title %}容器镜像包列表{% endblock %}


{% block header %}
    <link rel="stylesheet" type="text/css" href="{% static 'plugins/fileinput/css/fileinput.css'%}">

{% endblock header %}



{% block left %}
    {% include "base/_left.html" with cmdb_docker_image_file_active="active" %}
{% endblock left %}

{% block page-content %}

    <div class="row wrapper border-bottom white-bg page-heading">
        <div class="col-lg-10">
            <h2>资产管理</h2>
            <ol class="breadcrumb">
                <li>
                    <a href="/">主页</a>
                </li>
                <li>容器管理</a>
                </li>
                <li class="active">
                    <strong>容器镜像包列表</strong>
                </li>
            </ol>
        </div>

    </div>
    <div class="wrapper wrapper-content animated fadeInRight">
        <div class="row">
            <div class="col-lg-12">
                <div class="ibox">
                    <div class="ibox-title">
                        <h5>镜像包文件列表</h5>
                    </div>
                    <div class="ibox-content">

                        <div class="col-md-2">
                            <a class="btn btn-primary" id="upload_file" data-toggle="modal" data-target="#fileModal">手工上传镜像包</a>
                        </div>
                        <div class="col-md-8 form-inline">
                            <label class="text-success">更新到宿主机:</label>
                            <select id="dockerhost" class="form-control">
                                <option value="">-------------</option>
                                {% for row in dockerhosts %}
                                <option value="{{ row.id }}">{{ row }}</option>
                                {% endfor %}
                            </select>
                            - <a class="btn btn-success" id="copy_all" data-toggle="modal" data-target="#myModal">批量复制/还原</a>

                        </div>
                        <table class="table table-striped table-bordered table-hover" id="tb">
                            <thead>
                            <tr>
                                <th width="20"><input type="checkbox" id="CheckedAll"></th>
                                <th>名称</th>
                                <th>版本</th>
                                <th>来源</th>
                                <th>文件名</th>
                                <th>大小</th>
                                <th class="col-lg-2">动作</th>
                            </tr>
                            </thead>
                            <tbody>

                            {% for row in object_list %}

                                <tr>
                                    <td><input type="checkbox" value="{{ row.id }}"  name="id"></td>
                                    <td class="center">{{ row.name }}
                                    </td>
                                    <td class="center">{{ row.ver }}</td>
                                    <td class="center">{{ row.dockerhost }}</td>
                                    <td class="center">{{ row.file }}</td>
                                    <td class="center">{{ row.size|filesizeformat }}</td>
                                    <td>
                                        <button type="button" class="btn btn-success btn-xs" data-toggle="modal" data-target="#myModal">复制</button>
                                        <button type="button" class="btn btn-danger btn-xs" data-toggle="modal" data-target="#myModal">删除</button>

                                    </td>
                                </tr>
                            {% endfor %}

                            </tbody>

                        </table>

                    </div>
                </div>
            </div>
        </div>
    </div>


    <!-- 操作返回 - 模态框（Modal） -->
    <div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <button type="button" class="close" data-dismiss="modal" aria-hidden="false">
                        &times;
                    </button>
                    <span id="server"></span>
                </div>
                <div class="modal-body">
                    <textarea id="server_msg" readonly style="width:100%;" rows="5">{{ text }}</textarea>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-default" data-dismiss="modal">关闭
                    </button>
                </div>
            </div>
        </div>
    </div>


    <!-- 手工上传镜像包 Modal -->
    
    <div class="modal fade" id="fileModal" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true">
        <div class="modal-dialog modal-lg" role="document">
            <div class="modal-content">
                <form method="post" enctype="multipart/form-data">
                    <div class="modal-header">
                        <h5 class="modal-title" id="exampleModalLabel">上传镜像包</h5>
                        <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                            <span aria-hidden="true">&times;</span>
                        </button>
                    </div>
                    <div class="modal-body">
                        {% csrf_token %}
                        <div class="file-loading">
                            <input id="imagefile" name="imagefile" multiple type="file">
                        </div>
                        <div id="kartik-file-errors"></div>
                    </div>
                    <div class="modal-footer">
                        <button class="btn btn-success" type="button" id="submit_upload">提交</button>
                        <button type="button" class="btn btn-secondary" data-dismiss="modal">取消</button>
                        <div id="upload_div" style="display:none">
                            <hr class="hr-line-dashed" />
                            <h5 class="modal-title" id="exampleModalLabel">返回信息</h5>
                            <textarea id="upload_msg" readonly style="width:100%;" rows="5">{{ text }}</textarea>
                        </div>
                    </div>
                </form>
            </div>
        </div>
    </div>




{% endblock page-content %}


{% block footer-js %}
    <script src="{% static 'plugins/fileinput/js/fileinput.js'%}" type="text/javascript"></script>
    <script src="{% static 'plugins/fileinput/js/locales/zh.js'%}" type="text/javascript"></script>

    <script>
        function conn_docker(url, textarea_height){
            $.ajax({
                url: url,
                type: 'GET',
                timeout: 360*1000,  //毫秒
                error: function(){
                    $("#server_msg").val('网站连接超时，可能镜像包文件较大，需要较多上传时间，\r\n当前超时并不影响后端镜像继续下载，请隔一会再查看有否有镜像包。');
                },
                success: function(msg_html){
                    // json格式化
                    // console.log(msg_html);
                    $('#server_msg').val(msg_html);
                    // console.log(txt);
                    $('#server_msg')[0].style.minHeight= textarea_height;

                }
            });
        };

        $(document).ready(function(){

            // $( ".btn-danger.btn-xs" ).click()
            $('#tb').on('click', 'button', function (e) {
                // console.log($(this));
                var id=this.parentElement.parentElement.children[0].children[0].value;
                var url="{% url 'dock:docker_imagefile_list' %}"+id;
                var textarea_height="200px";
                $("#server").text(this.parentElement.parentElement.children[1].textContent+" "+this.textContent);
                if (this.className=="btn btn-danger btn-xs") {
                    if(! window.confirm('确认删除镜像包？')){
                        return false;
                    }
                    textarea_height="100px";
                    url=url+'/del/';
                    // console.log(id);
                    // return false;
                    return conn_del(url);
                } else if (this.className=="btn btn-success btn-xs") {
                    // 单个镜像复制
                    hostid=get_dockerhost_id();
                    if(! hostid){return false;}
                    if(! window.confirm('确认复制/还原镜像包到宿主机？\r\n宿主机上若有相同(名称:版本)镜像将会被当镜像包替换。')){
                        return false;
                    }
                    url=url+'/load/'+hostid;
                    // console.log(url);
                    conn_docker(url, textarea_height);
                    $("#server_msg").val("正在上传镜像到宿主机，请稍候……\r\n若镜像文件容量大，可能需要较长时间.");
                }

            });



            $("#copy_all").click(function(){
                // 批量镜像复制到宿主机
                hostid=get_dockerhost_id();
                if(! hostid){return false;}
                var ids = '';
                var objs=document.getElementsByName('id');
                for (i=0; i < objs.length; i++) {
                    if (objs[i].checked) {
                        ids = ids+objs[i].value+',';
                        // console.log(objs[i].value);
                    }
                }
                if (! ids) {alert("未选择任何镜像包");return false;}
                if(! window.confirm('确认批量复制/还原镜像包到宿主机？\r\n宿主机上若有相同(名称:版本)镜像将会被当镜像包替换。')){
                    return false;
                }
                console.log(ids);
                var url="{% url 'dock:docker_imagefile_list' %}"+ids+'/load/'+hostid;
                console.log(url);
                conn_docker(url, textarea_height="200px");
                $("#server_msg").val("正在上传镜像到宿主机，请稍候……\r\n若镜像文件多、容量大，可能需要较长时间.");

            });



            // $("#upload_file").click(function(){
            //     // 手工上传镜像包
            //     hostid=get_dockerhost_id();
            //     if(! hostid){return false;}

            // });



            $("#submit_upload").click(function(){
                // 提交文件上传，验证处理
                // console.log($(this));
                var obj=$("#imagefile");
                // console.log(obj.val());
                if(! obj.val()){return false;}
                $("#upload_div").show();

                // 转为Ajax处理POST上传文件
                var post_data = new FormData();
                post_files = document.getElementById("imagefile").files;
                for (var i=0;i<post_files.length;i++) {
                    // console.log(post_files[i]);
                    post_data.append("imagefile", post_files[i]);
                }
                $.ajax({
                    url: "{% url 'dock:docker_imagefile_upload' %}",
                    type: 'POST',
                    data: post_data,
                    contentType: false,
                    processData: false,
                    timeout: 240*1000,
                    error: function(){
                        $("#upload_msg").val('网站连接超时，可能镜像包文件过大，需要较多上传时间，\r\n对于大文件建议单次只上传一个。');
                    },
                    success: function(msg_html){
                        // console.log(msg_html);
                        $('#upload_msg').val(msg_html);
                        $('#upload_msg')[0].style.minHeight= "200px";

                    }
                })
                // this.form.submit();

            });



            $("#imagefile").fileinput({
                // 手工上传镜像包 bootstrap-fileinput插件参数定义
                // theme: 'fa',
                // rtl: true,
                showPreview: false,
                showUpload: false,
                elErrorContainer: '#kartik-file-errors',
                allowedFileExtensions: ["tar", "bz2", "gz"],
                language: 'zh',
                browseClass: "btn btn-success",
                // browseClass: "btn btn-primary btn-lg",
                maxFileCount: 3,
                // maxFileSize: 1024*1024,
                //uploadUrl: '/site/file-upload-single'
            });



        });


    function get_dockerhost_id(){
        var dockerhost=$('#dockerhost');
        hostid=dockerhost.select().val();
        // console.log(hostid);
        if (! hostid){
            alert("请选择需要更新镜像的宿主机");
            dockerhost.focus();
            return;
        }
        return hostid;
    }

    function conn_del(url){
        // 提交删除
        console.log(url);
        // return false;
        $.ajax({
            url: url,
            type: 'GET',
            timeout: 20000,
            error: function(){
                $("#server_msg").val('网站连接失败！请联系CMDB管理员');
            },
            success: function(msg_html){
                $("#server_msg").val(msg_html);
                var msg = JSON.parse(msg_html);
                // console.log(msg.remove);
                if (msg.remove=="ok") {
                    // 删除成功，刷新页面
                    location.reload()
                }
            }
        });

    }



    </script>

{% endblock footer-js %}

